//
//  LiChengVC.m
//  
//
//  Created by 000 on 16/10/20.
//
//

#import "LiChengVC.h"

//#import "QZWGS84TOGCJ02.h"

#import "QZAnnotation.h"
#import "QZAnnotationView.h"
#import "QZCancleVC.h"
#import "QZChooseView.h"
#import "constant.h"
#import "BmobSDK/Bmob.h"
#import <BmobSDK/BmobFile.h>
#import <BmobSDK/BmobObject.h>
#import "UIView+Extestion.h"
#import "UIBarButtonItem+Extension.h"
/***
 
    需要加载的东西
 
 ***/
@interface LiChengVC ()<MKMapViewDelegate,CLLocationManagerDelegate,QZChooseViewDelegate>
{
    
    NSUserDefaults *userDefaults1;
    
    NSMutableArray *personDeskArray;
    NSMutableArray *personClArray;
    NSMutableArray *deskImArray;//任务图片、
    NSMutableArray *thirdOderArray;//每一组中的个数
    NSMutableArray *showDeskArray;//需要显示的数据
    NSMutableArray *showPartCLArray;//显示坐标的子数组
    NSMutableArray *showClArray;//显示坐标的总数组
    NSMutableArray *showAreaArray;//面积坐标数组
    
    NSMutableArray *allGroupCOuntArr;//所有数组中个数的数组
    
    int personGroupCount;//改组中有几个数据
    int startGroupCount;//第几个开始
    
    
//    MKPolyline *grayLine;
    
}

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@property (nonatomic, strong) CLLocationManager *locationManager;//定位坐标
@property (nonatomic, strong) QZChooseView *chooseView;
- (IBAction)pointBC:(id)sender;
- (IBAction)lineBC:(id)sender;
- (IBAction)areaBC:(id)sender;
@end

@implementation LiChengVC


- (CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate = self;
        //每隔多远定位一次
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        
        [_locationManager startUpdatingLocation];
        //精确度
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    }
    return _locationManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"里程";
    [self location];
    //右侧图片  /**没有图片 原来的导航栏被覆盖了*/
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(popView) image:@"nav_right" hignImage:@"nav_right"];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(dismiss) image:@"nav_left" hignImage:@"nav_left"];
    userDefaults1 = [NSUserDefaults standardUserDefaults];
    self.chooseView = [QZChooseView chooseViewWithFrame:CGRectMake(kScreenW, 0, kScreenW, kScreenH)];
    self.chooseView.delegate = self;
    startGroupCount = 0;
    [self loadPersonData];
    [self loadThirdOrderData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.chooseView hide];
}

- (void)loadPersonData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"personDesk"];
    [query orderByAscending:@"createdAt"];
    [query whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        personDeskArray = [NSMutableArray array];
        personClArray = [NSMutableArray array];
        deskImArray = [NSMutableArray array];
        NSString *deskImaStr;
        
        for (BmobObject *obj in array) {
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.coordinate = CLLocationCoordinate2DMake([[obj objectForKey:@"latitude"] doubleValue], [[obj objectForKey:@"longitude"] doubleValue]);
            deskImaStr = [obj objectForKey:@"deskImStr"];
            CLLocation *pCl = [[CLLocation alloc] initWithLatitude:deskAn.coordinate.latitude longitude:deskAn.coordinate.longitude];
            [personClArray addObject:pCl];
            [personDeskArray addObject:deskAn];
            [deskImArray addObject:deskImaStr];
        }
    }];

}

- (void)loadThirdOrderData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"thirdOrder"];
    [query orderByAscending:@"createdAt"];
    [query whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        thirdOderArray = [NSMutableArray array];
        
        NSString *thirdOrderStr;
        for (BmobObject *obj in array) {
            
            thirdOrderStr = [obj objectForKey:@"groupCountStr"];
            
            [thirdOderArray addObject:thirdOrderStr];
        }
    }];
    
}
#pragma mark 跟踪自己的位置
- (void)location
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.026416, 0.019511);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.currentCoordinate, span);
    [self.mapView setRegion:region animated:YES];
    //显示用户的位置
    self.mapView.showsUserLocation = YES;
    //    self.mapView.mapType = MKMapTypeStandard;
    //追踪用户的位置
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.currentCoordinate = userLocation.coordinate;
}
#pragma mark 制作大头针
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //如果是当前位置就设置为nil
    if (annotation == mapView.userLocation) {
        return nil;
    }else{
        QZAnnotation *myAnnotation = [[QZAnnotation alloc] init];
        myAnnotation = annotation;
        QZAnnotationView *myAnnotationView = [QZAnnotationView getQZAnnotationViewWithMapView:mapView andAnnotation:annotation];
        
        myAnnotationView.image = [UIImage imageNamed:@"desk"];
        [myAnnotationView.leftButton setBackgroundImage:myAnnotation.image forState:UIControlStateNormal];
        return myAnnotationView;
    }
    
}
#pragma mark - MKMapViewDelegate
//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
//{
//    return nil;
//}
#pragma mark - CLLocationManagerDelegate
#pragma mark 自己位置的代理方法
#pragma mark - MKMapViewDelegate
#pragma mark - MKMapViewDelegate 给坐标添加图层的方法
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *lineRender = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        lineRender.lineWidth = 3;
        lineRender.strokeColor = [UIColor grayColor];
        return lineRender;
    } else if ([overlay isKindOfClass:[MKPolygon class]]){
    
        MKPolygonRenderer *polygonRender = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
        polygonRender.lineWidth = 3;
        polygonRender.strokeColor = [UIColor yellowColor];
        polygonRender.fillColor = [UIColor colorWithRed:0 green:0 blue:0.8 alpha:0.3];
        return polygonRender;
    }
    return nil;
}
#pragma mark QZChooseViewDelegate
/**
 *  chooseView的代理方法
 *
 *  @param chooseView        chooseView
 *  @param selectedArray     在tabeleView中被选中的数组
 *  @param loadGroupCountArr 每组中的个数
 */
- (void)chooseView:(QZChooseView *)chooseView didDoneBtnClickWithSelectedArray:(NSMutableArray *)selectedArray groupCountArray:(NSMutableArray *)loadGroupCountArr
{
    allGroupCOuntArr = [NSMutableArray array];
    allGroupCOuntArr = loadGroupCountArr;
    
    showAreaArray = [NSMutableArray array];
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    
    
        showClArray = [NSMutableArray array];
    //遍历selectedArray  得到被选中的是哪一组
    for (int i=0; i<selectedArray.count; i++) {
        startGroupCount =0;
        personGroupCount = 0;
        showPartCLArray = [NSMutableArray array];
        showDeskArray = [NSMutableArray array];

        int x = [selectedArray[i] intValue];//x代表的是第几组的
        
        for (int j=0; j<thirdOderArray.count; j++) {//这儿遍历的所有组数
            if (j<x) {
                startGroupCount = startGroupCount+[thirdOderArray[j] intValue];
            }
        }
        personGroupCount = [loadGroupCountArr[i] intValue];
        
        for (int k=0; k<personDeskArray.count; k++) {//遍历persinDesk中的数据
            if (k>=startGroupCount&&k<startGroupCount+personGroupCount) {
                [showDeskArray addObject:personDeskArray[k]];
                [showPartCLArray addObject:personClArray[k]];
            }
            
        }
        [showClArray addObject:showPartCLArray];
        
        
        [self.mapView addAnnotations:showDeskArray];
        [showAreaArray addObjectsFromArray:showPartCLArray];
        self.navigationItem.title = [NSString stringWithFormat:@"共有%d个点",(int)showPartCLArray.count];
    }
}

- (void)popView
{
    [self.chooseView show];
}
- (void)dismiss
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)pointBC:(id)sender {
    if (showClArray.count!=0) {
        self.navigationItem.title = [NSString stringWithFormat:@"共有%d个点",(int)showPartCLArray.count];
        [self.mapView removeOverlays:self.mapView.overlays];
    }
}

- (IBAction)lineBC:(id)sender {
    if (showPartCLArray.count!=0) {
        //设置标题
        CLLocationDistance distance;
        distance = [self getMargin];
        self.navigationItem.title = [NSString stringWithFormat:@"共走了%dKM",(int)distance];
        //加线
        [self.mapView removeOverlays:self.mapView.overlays];
        for (int i =0; i<showClArray.count; i++) {
            NSMutableArray *showArray = [NSMutableArray array];
            showArray = showClArray[i];
            
            int pointCount = (int)showArray.count;
            CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
            for (int i = 0; i<pointCount; ++i) {
                CLLocation *location = [showArray objectAtIndex:i];
                coordinateArray[i] = [location coordinate];
            }
            MKPolyline *grayLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mapView addOverlay:grayLine];
                [self.mapView setVisibleMapRect:[grayLine boundingMapRect] animated:YES];
            });
        }
    }
}
- (CLLocationDistance)getMargin
{
    CLLocation *lastLocation;
    CLLocationDistance distance;
    for (int i =0; i<showPartCLArray.count-1; i++) {
        lastLocation = showPartCLArray[i];
        distance += [lastLocation distanceFromLocation:showPartCLArray[i+1]];
        NSLog(@"%f",distance);
    }
    return distance;
}
- (IBAction)areaBC:(id)sender {
    if (showClArray.count!=0) {
        self.navigationItem.title = [NSString stringWithFormat:@"共有%d个点",(int)showPartCLArray.count];
        [self.mapView removeOverlays:self.mapView.overlays];
        int pointCount = (int)showAreaArray.count;
        CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
        for (int i = 0; i<pointCount; ++i) {
            CLLocation *location = [showAreaArray objectAtIndex:i];
            coordinateArray[i] = [location coordinate];
        }
        MKPolygon *polygonView = [MKPolygon polygonWithCoordinates:coordinateArray count:pointCount];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mapView addOverlay:polygonView];
            [self.mapView setVisibleMapRect:[polygonView boundingMapRect] animated:YES];
        });
    }
}

@end
